<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Preview</title>
    <!-- es-module-shims -->
  </head>
  <body>
    <script>
      window.addEventListener("message", ({ data }) => {
        if (data?.type === "update") {
          const importmapTag = document.querySelector(
            'script[type="importmap"]'
          );
          if (data.data.importmap) importmapTag.innerHTML = data.data.importmap;

          // 获取样式代码块
          const appStyleTags =
            document.querySelectorAll('style[id^="style_"]') || [];
          // 获取脚本代码块
          const appSrcTag = document.querySelector("#appSrc");
          // 获取旧的脚本地址
          const oldSrc = appSrcTag.getAttribute("src");
          // 移除旧的脚本
          appSrcTag.remove();
          // 创建新的脚本
          const script = document.createElement("script");
          // 创建新的脚本地址
          const newSrc = URL.createObjectURL(
            new Blob([data.data.compileCode], {
              type: "application/javascript",
            })
          );
          // 设置新的脚本地址
          script.src = newSrc;
          script.id = "appSrc";
          script.type = "module";
          // 脚本加载完后移除旧的样式
          script.onload = () => {
            appStyleTags.forEach((div) => {
              div.remove();
            });
          };
          // 添加新的脚本
          document.body.appendChild(script);
          // 释放旧的脚本地址
          URL.revokeObjectURL(oldSrc);
          // 通知父窗口加载完成
          window.parent.postMessage({ type: "done", message: "" });
        }
      });
      // 捕获错误 通知父窗口
      window.addEventListener("error", (e) => {
        window.parent.postMessage({ type: "error", message: e.message });
      });

    </script>
    <script type="importmap"></script>
    <script type="module" id="appSrc"></script>
    <div id="root">
      <div
        style="
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          display: flex;
          justify-content: center;
          align-items: center;
        "
      >
        Loading...
      </div>
    </div>
  </body>
</html>
